package tools.tree;

import java.util.ArrayList;

public class InternalTreeNode {

	private boolean isLeaf,hasBranchlength,hasLabel;
	private String label;
	private InternalTreeNode parent;
	private ArrayList<InternalTreeNode> children;
	private double x;
	private double y;
	private double r;
	private double theta;
	private double branchlength;
	private int id;
	private int level;
	
	public InternalTreeNode(InternalTreeNode parent,int id){
		this.parent=parent;
		this.id=id;
		isLeaf=true;
		hasBranchlength=false;
		hasLabel=false;
		x=0;
		y=0;
		r=0;
		theta=0;
	}
	
	public void addChild(InternalTreeNode child){
		if(isLeaf){
			children=new ArrayList<InternalTreeNode>();
			children.add(child);
			isLeaf=false;
		}else{
			children.add(child);
		}
	}
	
	/**
	 * reverses the order of the children 
	 *
	 */
	public void reverseChildren(){
		ArrayList<InternalTreeNode> tmp=new ArrayList<InternalTreeNode>();
		for (InternalTreeNode node : children) {
			tmp.add(0, node);
		}
		children=tmp;
	}
	
	public String toString(){
		if(isLeaf()){
			return (hasLabel()?getLabel():"") + (hasBranchlength()?":"+getBranchlength():"")+";";
		}else{
			String tmp=children.get(0).toString();
			String ret="("+tmp.substring(0, tmp.length()-2);
			for(int i=1;i<children.size();i++){
				tmp=children.get(i).toString();
				ret+=","+tmp.substring(0, tmp.length()-2);
			}
			return ret+")"+ (hasLabel()?getLabel():"")+ (hasBranchlength()?":"+getBranchlength():"")+";";
		}
	}
	
	public boolean equals(InternalTreeNode b){
		if(b==null){
			return false;
		}
		return this.id==b.getId();
	}

	public ArrayList<InternalTreeNode> getChildren(){
		return children;
	}
	public boolean isLeaf(){
		return isLeaf;
	}
	public String getLabel() {
		if(hasLabel()){
			return label;
		}else{
			return "";
		}
	}

	public boolean hasLabel(){
		return hasLabel;
	}
	public void setLabel(String label) {
		hasLabel=true;
		this.label = label;
	}

	public InternalTreeNode getParent() {
		return parent;
	}

	public void setParent(InternalTreeNode parent) {
		this.parent = parent;
	}

	public double getR() {
		return r;
	}

	public void setR(double r) {
		this.r = r;
	}

	public double getTheta() {
		return theta;
	}

	public void setTheta(double theta) {
		this.theta = theta;
	}

	public double getX() {
		return x;
	}

	public void setX(double x) {
		this.x = x;
	}

	public double getY() {
		return y;
	}

	public void setY(double y) {
		this.y = y;
	}
	public int getId(){
		return id;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public double getBranchlength(){
		if(hasBranchlength){
			return branchlength;
		}else{
			return -1;
		}
	}

	public boolean hasBranchlength(){
		return hasBranchlength;
	}
	public void setBranchlength(double branchlength) {
		hasBranchlength=true;
		this.branchlength = branchlength;
	}
	
}
